//
//  PrescribeCell.swift
//  TCMHealth
//
//  Created by 韩颖 on 2023/7/12.
//

import UIKit
import Foundation
import HXPHPicker

class PrescribeCell: UITableViewCell {
    
    @IBOutlet weak var medicenTitleLabel: UILabel!
    @IBOutlet weak var photoContentView: UIView!
    @IBOutlet weak var prescribeTextView: UITextView!
    @IBOutlet weak var photoContentHeight: NSLayoutConstraint!
    var photoView: SinaPhotoView!
    var assetArray = [PhotoAsset]()
    var imageUrlArray:[String] = []
    var updateCell: (() -> Void)?
    var addMedication: (() -> Void)?
    var gotoMedicine: (() -> Void)?
    @IBOutlet weak var medicinesView: UIView!
    @IBOutlet weak var medicineSuperView: UIView!
    @IBOutlet weak var medicineHeight: NSLayoutConstraint!
    @IBOutlet weak var medicineContentHeight: NSLayoutConstraint!
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.photoView = SinaPhotoView.init(frame: CGRect(x: 20, y: 10, width: photoContentView.width - 40, height: 90))
        self.photoContentView.addSubview(photoView)
        self.photoView.model = .LocalEdit
        self.photoView.deleteBtnClosure = { [unowned self] index , model ,imageView in
            assetArray.remove(at: index)
            updatePhotoView()
            self.updateCell?()
        }
        
        photoView.clickClosure = { [unowned self] index , imageView ,imageModel in
            print("clickIndex = ", index)
            presentPreViewController(currentIndex: index)
            
        }
        let tapges = UITapGestureRecognizer(target: self, action: #selector(gotoMedicineView))
        medicineSuperView.addGestureRecognizer(tapges)
    }
    
    @objc func gotoMedicineView() {
        gotoMedicine?()
    }
    
    func updatePhotoView() {
        photoContentView.isHidden = assetArray.count == 0
        photoContentHeight.constant = assetArray.count == 0 ? 0 : 110
    }
    
    @IBAction func addPhoto(_ sender: Any) {
        self.presentPickerController()
    }
    
    func setPrintMedicines(_ medicinesTtile:String = "暂无处方名", medicines: [String:String]) {
        medicenTitleLabel.text = medicinesTtile
        if medicines.keys.count > 0 {
            medicineSuperView.isHidden = false
            medicinesView.isHidden = false
            var row: Int = -1
            var col: Int = 0
            let labelH: CGFloat = 20.0
            let maginW: CGFloat = 20.0
            let maginH: CGFloat = 10.0
            for (medicineKey,medicineWidth)  in medicines {
                let labelW = (medicinesView.width - 40) / 3
                row += 1
                col = Int(row / 3)
                
                let label = UILabel(frame:  CGRectMake(CGFloat(row) * (maginW + labelW), CGFloat(col) * (labelH + maginH), labelW, labelH))
                label.text = medicineKey + "  " + medicineWidth
                medicinesView.addSubview(label)
            }
            medicineContentHeight.constant = (CGFloat(col) * (labelH + maginH) + labelH) + 10
            medicineHeight.constant = 50 + (CGFloat(col) * (labelH + maginH) + labelH)
        }else {
            medicineSuperView.isHidden = true
            medicineHeight.constant = 0
            medicinesView.isHidden = true
        }
        
    }
    
    func presentPickerController() {
        // 设置与微信主题一致的配置
        let config = PhotoTools.getWXPickerConfig()
        config.maximumSelectedCount = 4
        let pickerController = PhotoPickerController(picker: config)
        pickerController.pickerDelegate = self
        // 当前被选择的资源对应的 PhotoAsset 对象数组
        pickerController.selectedAssetArray = assetArray
        // 是否选中原图
        pickerController.isOriginal = false
        self.getViewOnController().present(pickerController, animated: true, completion: nil)
    }
    
    
    func presentPreViewController(currentIndex: Int) {
        let config = PickerConfiguration.init()
        let preViewController =
        PhotoPickerController(preview: config, currentIndex: currentIndex, modalPresentationStyle: .overFullScreen, delegate: self)
        preViewController.selectedAssetArray = self.assetArray
        self.getViewOnController().present(preViewController, animated: true, completion: nil)
    }
    
    @IBAction func addMedication(_ sender: Any) {
        self.addMedication?()
    }
    
}

    
    
extension PrescribeCell: PhotoPickerControllerDelegate {
    
    /// 选择完成之后调用
    /// - Parameters:
    ///   - pickerController: 对应的 PhotoPickerController
    ///   - result: 选择的结果
    ///     result.photoAssets  选择的资源数组
    ///     result.isOriginal   是否选中原图
    func pickerController(_ pickerController: PhotoPickerController,
                          didFinishSelection result: PickerResult) {
        result.getImage { (image, photoAsset, index) in
            if let image = image {
                print("success", image)
                if !self.assetArray.contains(photoAsset) {
                    self.assetArray.append(photoAsset)
                    self.imageUrlArray.append(photoAsset.localImageAsset?.imageURL!.absoluteString ?? "")
                    self.photoView.addPhotoModels(photoModels: [SinaPhotoView.PhotoModel(img: image, interfaceModel: nil)])
                }
            }else {
                print("failed")
            }
        } completionHandler: { (images) in
           
            self.updatePhotoView()
            self.updateCell?()
        }
    }
    
    /// 点击取消时调用
    /// - Parameter pickerController: 对应的 PhotoPickerController
    func pickerController(didCancel pickerController: PhotoPickerController) {
        
    }
}

